<?php
/*
 * Created on Feb 5, 2009
 * @author: ANH
 * @PARAM rtype is rootType: example: caves is type then attraction is rtype
 * @filesource: modules/place/controllers/PlaceController.php
 */
class Place_MasterController extends Clu_Controller_Action_Master
{
	public function init()
	{
		//require_once  (APP_PATH.'/modules/article/Model/Article.php');
		//require_once  (APP_PATH.'/modules/category/Model/Category.php');
		//require_once  (APP_PATH.'/modules/comment/Model/Comment.php');
		//require_once  (APP_PATH.'/modules/user/Model/User.php');
		
		$this->m = new place_Model_Place();
		$this->mCity = new place_Model_City();
		$this->mDistrict = new place_Model_District();
		$this->mVillage = new place_Model_Village();
		$this->mArticle = new article_Model_Service();
		$this->mCategory = new category_Model_Category();
		$this->mCategory->setTables('place');
		$this->mComment = new comment_Model_Service();
		$this->mVicinity = new place_Model_Vicinity();
		parent::init();
	}
	
    public function newAction() 
    {
       	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'create place') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
		
	    //TODO: what for?
    	$auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
	    
        $this->viewParams['form'] = new place_Form_Place();
        $actionUrl = $this->hvnUrl(array('module' => 'place', 'action'=>'new'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'new', 'action_url' => $actionUrl, 
							  'userPermissions' => $sess->userPermissions, 
							  'language' => $sess->viewLang ));
     	$this->viewParams['errorMessage'] = '';
        $formName = 'place_Form_Place';
        $data = $this->_request->getParams();
		//if valid data     
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST)) 
	    {
	    	//get type 
        	$ret = $this->mCategory->getTree($data['rtype'], 2, 2);
	    	//TODO: change this to become part of form validation
	    	if($data['rtype'] == 0)
	    	{
	    		$this->viewParams['errorMessage'] = t(129)." <br/>";
	    	}	
	        else if(!empty($ret) && !empty($data['type']))
	        {
        		$data['type'] = implode(",",$data['type']);
	        }
	        
	        //check: has place already?
	        if(	$this->m->checkPlace($data['name']) === false)
    		{
    			$this->viewParams['errorMessage'] = t(722)." <br/>";
    		}
	    		
	        $db = $this->db;
	        $db->beginTransaction();
            try 
            {
            	$t['article_title'] = $data['name'];
				$t['article_language'] = $data['language'];
				$t['article_module'] = 'place';
	        	$t['article_status'] = isset($data['status']) ? $data['status'] : 
        			Zend_Registry::get('configuration')->general->defaultNodeStatus;
            	//insert article_title
                if (!$this->mArticle->insertRaw($t,false))
                {
                	$this->viewParams['errorMessage'] = t(503);
                }
                $article_id = $db->lastInsertId();
                
                //insert place
    			if($article_id != 0)
                {
                	$data['article_id'] = $article_id;
	                $data['poster_id'] = $uIdentity->id;
		            try
			    	{
			    		$options = array('do_validate' => false);
		    			$placeId = $this->m->insertRaw($data, $options);
			    	}
			    	catch (Exception $e) 
			    	{
			    		$this->mArticle->deleteByPrimary(array($article_id), false);
			    	    $this->viewParams['errorMessage'] = $e->getMessage() . "<br/>" . t(723);
			    	}
                }
                else
                {
                	die($this->viewParams['errorMessage']);
                }
                 
                 $db->commit();
            }
            catch (Exception $e)
            {
                $db->rollBack();
                $this->viewParams['errorMessage'] = $e->getMessage() . "<br/>". t(69);
            }
            if (empty($this->viewParams['errorMessage'])) //SUCCESSFUL
            {
    	    	$url = $this->view->hvnUrl(array('module'=>'place', 'action'=>'edit'));
    			$this->_helper->redirector->gotoUrl($url . '?id='.$placeId.'&j=1'); //TODO
            	return;
            }
		}
//		else
//			$this->viewParams['errorMessage'] = t(1);
		
		//Populate form & rtype options 
        $categoryId = $this->_request->getParam("rtype");
        $this->viewParams['form']->populateCategory($data, $categoryId );
		
        $this->viewParams['lang'] = $data['lang'];
		if(!empty($data['type']))
	        $this->viewParams['type'] = $data['type'];
        $this->viewParams['mode'] = "new";
    }
    
    public function viewAction() 
    {
    	if ($this->_request->getParam("view_city"))
    	{
    	     $this->viewParams["view_city"]  = $this->_request->getParam("view_city");
    		$this->presenceIdentifier = 2;
    		$this->paramsForWidgets["category_id"] = 14;
    		$cityId = $this->_request->getParam("id");
    		$this->paramsForWidgets["searchCondition"] = $cityId;
	        $searchData = array( array("key" => "city_id",
	        							"val" =>  $cityId,
										"valType" => "INTEGER",
										"searchType" => "equals"),
	        					array("key" => "type",
	        							"val" =>  "57",
										"valType" => "STRING",
										"searchType" => "equals"),
	        );
	        $result = $this->m->advancedFind($searchData);
	        $placeId  = $result['id'];
    	}
    	else
        	$placeId = $this->_request->getParam("id");
        	
		$sess = new Zend_Session_Namespace(CLU_NS);
		$dataDisplay = $this->m->getData($placeId, $options = null);
		$this->paramsForWidgets['place_id'] = $placeId;
		if(isset($dataDisplay['rtype']))
			$this->paramsForWidgets['rtype'] = $dataDisplay['rtype'];
		else
			$dataDisplay['rtype'] = null;
			
		if(isset($dataDisplay['city_id']))
			$this->paramsForWidgets['city_id'] = $dataDisplay['city_id'];
		else
			$dataDisplay['city_id'] = null;
		
		if(!isset($dataDisplay['district_id']))
			$dataDisplay['district_id'] = null;
		//$this->paramsForWidgets['district_id'] = $dataDisplay['district_id'];
		
		if(!isset($dataDisplay['type']))
			$dataDisplay['type'] = null;
			
		if(isset($dataDisplay['gallery']))
			$this->paramsForWidgets['gallery_id'] = $dataDisplay['gallery'];
		$this->paramsForWidgets['content_type'] = "place";
		$this->paramsForWidgets['content_id'] = $placeId;
		
		if(isset($dataDisplay['metadata']))
			$data = unserialize($dataDisplay['metadata']);
		if(isset($data['other_article']))
			$this->paramsForWidgets['listArticle'] = $data['other_article'];
		$dataplace = array('city_id' => $dataDisplay['city_id'],'district_id' => $dataDisplay['district_id'],
						   'rtype' => $dataDisplay['rtype'], 'type' => $dataDisplay['type']);
		$sess->searchParams->place = $dataplace;
        
        if(!$dataDisplay)
        {
            $this->renderError(null,t(724));
            return;
        }
        if(!empty($dataDisplay))
        {
	        //get data for display
	        //$place['article'] = $dataDisplay['article_data'];
	     //   die_a($this->mCity->getCityName($dataDisplay['city_id']));
//            $this->viewParams['city_name'] = $this->mCity->getCityName($dataDisplay['city_id']);
//             $this->viewParams['district_name'] = $this->mDistrict->getDistrictName($dataDisplay['district_id']);
//              $this->viewParams['village_id'] = $this->mVillage->getVillageName($dataDisplay['village_id']);
			//die_a($dataDisplay);
        	$this->viewParams['place'] = $dataDisplay;
        	
//	        die($this->viewParams['place']['poster_id']);
			if(isset($dataDisplay['category_name']['name']))
	        	$this->viewParams['categoryName'] = $dataDisplay['category_name']['name'];
	        $a = array();
	        if(isset($dataDisplay['type_name']))
	        {
		        foreach($dataDisplay['type_name'] as $k => $v)
		        {
			    $a[] = $v['name'];
		        }
	        }
	        $this->viewParams['typeName'] = $a;
	        
	        $this->paramsForWidgets['content_type'] = "place";
			$this->paramsForWidgets["type"] = "place";
			$this->paramsForWidgets["category"] = $dataDisplay['rtype'];
			$this->paramsForWidgets['content_id'] = $placeId;
	        $this->paramsForWidgets["id"] = $placeId;
	        $this->paramsForWidgets['content_poster_id'] = $dataDisplay['poster_id'];
	        if(isset($dataDisplay['article_data']['article_language']))
	        	$this->viewParams['oriLang'] = $dataDisplay['article_data']['article_language'];
	        $this->m->updateDbAfterView($placeId); //update view counts
	        //$this->renderToHolder('index/view.phtml', false, null, 4, 2);
        }
    }

    public function editAction()
    {
        $placeId = $this->_request->getParam('id');
        if (!$p = $this->m->findByPrimary($placeId))
        {
        	$this->viewParams['errorMessage'] = t(725);
        }
        //check for permission here. Check rights
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	if (!isset($sess->userId))
		{
		 	$this->renderError(null,t(726));
        	return;	
		}
		
		if (($sess->userId != $p->poster_id && strpos($sess->userPermissions, 'update place') === false) ||
				($sess->userId == $p->poster_id && strpos ($sess->userPermissions, 'update own place' ) === false))
		{
		 	$this->renderError(null,t(726));
        	return;	
		}
		
		if ($this->_request->getParam('j') == 1)
        {
        	$this->viewParams['justMessage'] = true;
        }
        $this->viewParams['form'] = new place_Form_EditPlace();
        $actionUrl = $this->hvnUrl(array('module' => 'place', 'action'=>'new'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'update', 'rtype' => $p->rtype, 'action_url' => $actionUrl,
        					  'userPermissions' => $sess->userPermissions, 'category' =>$p->rtype ));
        $formName = 'place_Form_EditPlace';
        if (!$this->_request->isPost())
        {
			//$fData = $this->m->getData($placeId, true, true);
            $this->viewParams['form']->populate($this->m->transformToFormArray($formName, $p));
        }
        else if ( $this->viewParams['form']->isValid($_POST))
        {
	    	$data = $this->_request->getParams();
        	// insert article
            $articleData = array();
            $articleData['article_title'] = $p->name;
            $keys = array('article_body', 'article_originality');
	        $articleData = clu_array_merge($keys, $data);
            
            if (!($this->mArticle->saveRaw(null, $articleData, $p->article_id, false)))
            {
            	$this->viewParams['errorMessage'] = t(503);
            }
			//all data was prepared. Now save the place data
		    try
		    {
		    	$this->m->saveRaw($p, $data, $placeId, array('do_validate' => false));
		    }
		    catch (Exception $e) 
            {
            	$this->viewParams['errorMessage'] = t(727);
            }
	        $this->view->successMessage = t(728);
			//populate form
			$this->viewParams['form']->populate($this->m->transformToFormArray($formName, $p));
        }
        else
        {
	    	$this->viewParams['errorMessage'] = t(71);
        }
        
        //get city_name and district_name
        $dataDisplay = $this->m->getData($placeId, $options = null );
        if(!empty($dataDisplay['city_name']))
			$this->viewParams['city_name'] = $dataDisplay['city_name'];
		if(!empty($dataDisplay['district_name']))
		$this->viewParams['district_name'] = $dataDisplay['district_name'];
        $this->viewParams['id'] = $placeId;
        $this->viewParams['placeName'] = $p->name;
        if(!empty($uIdentity->id))
        	$this->viewParams['uid'] = $uIdentity->id;
        $this->viewParams['rtype'] = $p->rtype;
        $this->viewParams['mode'] = "edit";
    }
    
    public function deleteAction() 
    {
        $id = $this->_request->getParam('id');
        $sess = new Zend_Session_Namespace(CLU_NS);
        //check user rights
       	if (strpos ($sess->userPermissions, 'delete place') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
	    
        if (!$p = $this->m->findByPrimary($id))
        {
        	$this->renderError(null,t(725));
        	return;	
        }
        if(!$this->m->deleteByPrimary($id))
        {
        	$this->renderError(null,t(729));
        	return;	
        }
        //$this->renderToHolder( 'common/success.phtml');
		
    }

 	public function searchAction()
    {
    	$requestData = $this->_request->getParams();
    	if(isset($requestData['cityId']))
    	{
    		$requestData['city_id'] = $requestData['cityId'];
    		$this->paramsForWidgets['city_id'] = $requestData['cityId'];
    	}
    	
    	if(isset($requestData['raw_name']))
    	{
    		$requestData['raw_name'] = $requestData['raw_name'];
    		$this->paramsForWidgets['raw_name'] = $requestData['raw_name'];
    	}
    	
    	$sess = new Zend_Session_Namespace(CLU_NS);
		$data = $this->prepareSearchData($requestData);
		if(isset($data['rtype']))
    	{
    		$this->paramsForWidgets['rtype'] = $data['rtype'];
    	}
		$this->paramsForWidgets['content_type'] = "place";
    	$this->viewParams['form'] = new place_Form_PlaceSearch();
		if (strpos($sess->userPermissions, "administer place"))
			$cluSearchMode = "fullAdminSearch";
	    else
			$cluSearchMode = "fullSearch";
		$actionUrl = $this->hvnUrl(array('module' => 'place', 'action'=>'search'), 'nocontroller') . "?cluSearch=1";
        $this->viewParams['form']->cluBuild(array('action' => 'search', 'action_url' => $actionUrl, 'cluSearchMode' => $cluSearchMode));
        $this->viewParams['form']->populateCategory($data);
        if (isset($data['cluSearch']) || $this->_request->isPost())
        {
		   	$select = $this->m->search($data);
			$paginator = $this->generatePaginator($select, $data['page'], $data['place_perpage'], 7, 'Jumping');
        	$searchUrl = encode_search_url($data, null, "place");
			$this->viewParams['searchUrl'] = 
			"http://" . SITE_URL . $this->view->hvnUrl(array('action' => 'search', 'module' => 'place'),'nocontroller') . "?$searchUrl";
        	
        }
		
		$this->viewParams['listCategory'] = $this->mCategory->getRootType('Root_Place');

		if(!empty($data['rtype']))
		{
			$this->viewParams['rtype'] = $data['rtype'];
			$this->viewParams['categoryName'] = $this->mCategory->getCategoryName($data['rtype']);
			$this->viewParams['listType'] = $this->mCategory->getTree($data['rtype'], 1, 1);
		}
		if(!empty($data['type']))
		{
			$this->viewParams['type'] = $data['type'];
			if(is_array($data['type']))
				$this->viewParams['string_type'] = implode(',', $data['type']);
			$this->viewParams['typeName'] = $this->mCategory->getCategoryName($data['type']);
		}
		$this->viewParams['listCity'] = $this->mCity->findForSelect();
		
		if(!empty($data['city_id']))
		{
			$this->viewParams['cityId'] = $data['city_id'];
			$this->paramsForWidgets['city_id'] = $data['city_id'];
			$cityName = $this->mCity->getCityName($data['city_id']);
			$this->viewParams['cityName'] = $cityName['city_name'];
			$this->viewParams['listDistrict'] = $this->mDistrict->getDistricts($data['city_id']);
			
			if(!empty($data['district_id']))
			{
				$this->viewParams['districtId'] = $data['district_id'];
				$this->viewParams['dist_Id'] = implode(',', $data['district_id']);
				$this->paramsForWidgets['district_id'] = $data['district_id'];
				foreach($data['district_id'] as $dis)
				{
					$districtName[$dis] = $this->mDistrict->getDistrictName($dis);
				}
				foreach($districtName as $disName)
					$district_Name[] = $disName['district_name'];
				$this->viewParams['districtName'] = implode(',', $district_Name);
			}
		}
		
		if(isset($data['raw_name']))
			$this->paramsForWidgets['raw_name'] = $data['raw_name'];
	    $this->viewParams['mode'] = 'search';	   
       //the results
       if(isset($paginator))
       {	
	       	$this->viewParams['paginator'] = $paginator;
			$this->viewParams['pList'] = $paginator->getCurrentItems();
			//get articles
			$articleList = array();
			$mArticle = new article_Model_Service();
			foreach ($this->viewParams['pList'] as $p)
			{
				$articleList[$p['id']] = $mArticle->getArticleData($p['article_id']);
			}
			unset($mArticle);
			$this->viewParams['aList'] = $articleList;
			/*
			$t = $this->_request->getParam('page');
			$pageNum  = !empty($t) ? $t : 1; 
			$perPage = isset($data['place_perpage']) ? $data['place_perpage']:  $data['place_perpage'];
			$this->viewParams['startIndex'] = $perPage * ($pageNum - 1);
			$this->viewParams['numberOfItems'] = $paginator->getTotalItemCount();
			$this->viewParams['perPage'] = $perPage;
			$this->viewParams['pageNum'] = $pageNum;
			$this->viewParams['numberOfPages'] = ceil($this->viewParams['numberOfItems']/$this->viewParams['perPage']);
			*/
			if(strpos ($sess->userPermissions, 'administer user'))
			{
				$this->presenceIdentifier = 2; //render 4--master--list-admin
				return;
			}
       }
    }
    
    public function successAction()
    {
        $this->viewParams['placeId'] = $this->_request->getParam("lastInsertId");
        //$this->renderToHolder('common/success.phtml');
    }
    
	public function editBasicAction()
    {
        $placeId = $this->_request->getParam('id');
        if (!$p = $this->m->findByPrimary($placeId))
        	$this->viewParams['errorMessage'] = t(725);
        //check for permission here. Check rights
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ((isset($uIdentity->id) != $p->poster_id && strpos ($sess->userPermissions, 'update place') === false) ||
				(isset($uIdentity->id) == $p->poster_id && strpos ($sess->userPermissions, 'update own place') === false))
		{
		 	$this->renderError(null,t(726));
        	return;	
		}
        
        $this->viewParams['form'] = new place_Form_Place();
        $actionUrl = $this->hvnUrl(array('module' => 'place', 'action'=>'edit-basic'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'edit-basic', 'action_url' => $actionUrl, 
							  'userPermissions' => $sess->userPermissions));
		$formName = 'place_Form_Place';
		if (!$this->_request->isPost())
		{
			$options = array('get_article' => true, 'get_vicinities' => false);
			$data = $this->m->getData($placeId, $options);
	        $categoryId = $this->mCategory->findParentId($data['rtype']);
			$this->viewParams['form']->populate($this->m->transformToFormArray($formName, $p));
			$this->viewParams['form']->populateCategory( $data, $categoryId);
		}
		
        elseif ($this->viewParams['form']->isValid($_POST))
        {	
        	$data = $this->_request->getParams();
        	$data['poster_id'] = $uIdentity->id;
        	// update article
        	$articleData = $this->m->transformToFormArray($formName, $p);
        	$articleData['article_title'] = $data['name'];
        	$articleData['article_language'] = $data['language'];
            if (!($this->mArticle->saveRaw(null, $articleData, $articleData['article_id'], false)))
            {
            	$this->viewParams['errorMessage'] = t(503);
            }
		    try
		    {
		    	if(!empty($data['type']))
		    		$data['type'] = implode(',', $data['type']);
		    	if ($this->m->saveRaw($p, $data, $placeId, false))
	            {
	            	$this->viewParams['successMessage'] = t(731);
	            }
		    	
		    }
		    catch (Exception $e) 
            {
                $this->viewParams['errorMessage'] = t(727);
            }
	        
	        $this->viewParams['form']->populateCategory( $data, $data['rtype'] );
        }
        else
        {
        	$this->viewParams['errorMessage'] = t(71);
        }
        	
        $this->viewParams['id'] = $placeId;
        $this->viewParams['rtype'] = $p->rtype;
        $this->viewParams['placeName'] = $p->name;
        $this->viewParams['type'] = explode(',',$p->type);
        $this->viewParams['mode'] = "edit";
        $this->viewParams['name'] = isset($uIdentity->name);
        
        //$this->renderToHolder( 'index/new.phtml', false, null, 4, 1);                 
    }    
    
    public function galleryAction()
    {
        $placeId = $this->_request->getParam('id');
        $sess = new Zend_Session_Namespace(CLU_NS);
	    if (!$p = $this->m->findByPrimary($placeId))
        {
        	$this->renderError(null,t(725));
        	return;	
        }
        //check user rights
       	if (strpos ($sess->userPermissions, 'update place') === false && 
       		($sess->userId != $p->poster_id)
       		)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
        
		//pas the gallery id to the gallery/widget/upload-photos        
        if ($p->gallery)
        {
			$this->paramsForWidgets["id"] = $p->gallery;
        }
        else
        {
        	$this->presenceIdentifier = 2; //Create a new gallery message
        	$this->paramsForWidgets["content_id"] = $placeId;
        	$this->paramsForWidgets["content_type"] = "place";
        }	
    }
   
	public function thumbnailAction()
    {
		$placeId = $this->_request->getParam("id");
		$place =  $this->m->findByPrimary($placeId);
		$this->viewParams['id'] = $placeId;
	   	if (!$place)
	   	{
   			$this->renderError(null, __("Could not find the place"));
   			return;
		}		
		if ($this->_request->isPost())
		{
			 $fileName = $_FILES['myFile']['name'];
			 if($_FILES['myFile']['name']){
				$posterId = $place['poster_id'];
				$ustoreDir = APP_PATH."/public/ustore/$posterId/images/original/place/$placeId/thumb/";
				if (!file_exists($ustoreDir))
							mkdir($ustoreDir, 0777  , true);
				$ufilesDir = APP_PATH."/public/ufiles/$posterId/images/original/place/$placeId/thumb/" ;
				if (!file_exists($ufilesDir))
							mkdir($ufilesDir, 0777  , true);
				$fileName = $_FILES['myFile']['name'];
				//make sure the file name is unique
				$targetFile = $ustoreDir . $fileName;
				$i = 1;
				while(file_exists($targetFile))
				{
								$fileName = $i . "_" . $_FILES['myFile']['name'];
								$targetFile = $ustoreDir . $fileName;	
								$i++;
				};
				move_uploaded_file($_FILES['myFile']['tmp_name'],$targetFile);
				//require_once APP_PATH."/library/common.php";
				$watermarkDir = APP_PATH."/public/watermark/";
				// now generate copies
				//TODO: if editors, then do watermark
				$ret = generate_image_copies ("ustore", $ustoreDir,$fileName, $watermarkDir, null, null, $posterId, false); //with wm		
				if ($ret == false)
				{
					//remove the uploaded files
			    	unlink ($targetFile);
					exit();
			    }
			    else
			    {
			        	//$this->viewParams['thumb'] = $targetFile;
			        	$thumb = str_replace(APP_PATH, "", $targetFile);
			        	$place->thumb = str_replace("/public/ustore/", "/public/ufiles/", $thumb);
			        	try 
			        	{
			        		$place->save();
			        	}
			        	catch (Exception $e)
			        	{
			        		die($e->getMessage());
			        	}
			   }
			}
		 }
		 if (!is_null($place->thumb))
			$this->viewParams['thumb'] = $place->thumb;
    }  
    
    
    public function travelInfoAction()
	{	
    }
    public function homeAction()
	{
	}
	
	/**
	 * This function merges all the previously saved search data & request params
	 * 
	 * @param: $requestData The search params that user submitted
	 * @return: Void Or $currentSearchData ?? TODO
	 */
	public function prepareSearchData($requestData)
	{
		$keys = array('language', 'id', 'raw_name','unaccented_name', 'city_id', 'district_id',
					  'article_id','fee','to_fee', 'other_name',
                      'fee_basis','fee_currency','payment_method', 'meals', 'delivery',
        	          'built_year','to_built_year', 'status', 'rating', 'desc',
        	          'rating_count', 'asc_or_desc', 'orderBy', 'user_id', 'getArticle');
		//other keys: 'city_id','district_id','village_id', 'str_number','str_name'
		//'type','rtype', 
		//$sess = new Zend_Session_Namespace(CLU_NS);
//		if(isset($sess->searchParams->place))
//			$currentSearchData = $sess->searchParams->place;
//		die_a($requestData);
		if(isset($requestData['district_id']))
		{
			if(is_array($requestData['district_id']))
				$requestData['district_id'] = array_unique($requestData['district_id']);
			else
				$requestData['district_id'] = explode(',', $requestData['district_id']);
		}
		
		if(isset($requestData['remove_district_id']) && isset($requestData['district_id']))
		{
			$removeDistrictId = explode(',', $requestData['remove_district_id']);
			foreach($removeDistrictId as $k => $removeDis)
			{
				if(empty($removeDis))
					unset($removeDistrictId[$k]);
				foreach($requestData['district_id'] as $k => $dis)
				{
					if($removeDis == $dis)
						unset($requestData['district_id'][$k]);
				}
			}
		}
		
		if(isset($requestData['type']))
		{
			if(is_array($requestData['type']))
				$requestData['type'] = array_unique($requestData['type']);
			else
				$requestData['type'] = explode(',', $requestData['type']);
		}
		
		if(isset($requestData['remove_type']) && isset($requestData['type']))
		{
			$removeType = explode(',', $requestData['remove_type']);
			foreach($removeType as $k => $rmType)
			{
				if(empty($rmType))
					unset($removeType[$k]);
				foreach($requestData['type'] as $k => $dis)
				{
					if($rmType == $dis)
						unset($requestData['type'][$k]);
				}
			}
		}
		
		//place list + pagination
		if (isset($requestData['place_perpage']))
			$currentSearchData['place_perpage'] = $requestData['place_perpage'];
		
		else if (!isset($currentSearchData['place_perpage']))
				$currentSearchData['place_perpage'] = $requestData['place_perpage'] = 10;
			else
			 	$requestData['place_perpage'] = $currentSearchData['place_perpage'];
			
		if (isset($requestData['page']))
			$currentSearchData['page'] = $requestData['page'];
		else
			$currentSearchData['page'] = $requestData['page'] = 1;
		
		if(isset($requestData['cluSearch']))
			$currentSearchData['cluSearch'] = $requestData['cluSearch'];
		
		//reset all params in session		
		if(isset($requestData['reset']) && $requestData['reset'] == 1)
		{
			//filter keyword
			$currentSearchData = $this->filterKeyword($requestData);
			return $currentSearchData ;
		}
		
		//$requestData['name'] = $requestData['search_name'];
		//No reset detected, now merge common keys first & don't unset values
		$currentSearchData = $this->mergeSearchValues($requestData, $currentSearchData, $keys, false); 
		//Address 
		/*
		$addressKeys = array(
						0 => 'city_id',
						1 => 'district_id',
						2 => 'village_id',
						3 => 'address5',
						4 => 'address6',
						5 => 'address7', //'str_name', 
						6 => 'address8', //TODO: get all 9 fields from address. See misc/docs/db.txt
						7 => 'address9'
					); 
					
		$currentSearchData = $this->mergeHierarchySearchValues($requestData, $currentSearchData, $addressKeys, 3);
		*/
		//type & rtype
		$categoryKeys = array(
						0 => 'category',
						1 => 'rtype',
						2 => 'type',
			);
		$currentSearchData = $this->mergeHierarchySearchValues($requestData, $currentSearchData, $categoryKeys, 2);
		
		//remove empty fields
		/*
		foreach ($currentSearchData as $k => $v)
		{
			if (empty($v))
				unset($currentSearchData[$k]);
		}
		*/
		//filter keyword
		$currentSearchData = $this->filterKeyword($requestData);
		
		return $currentSearchData;
	}
	
	/**
	 * Take $currentSearchData['raw_name'] to generate category (rtype, type)
	 * and a new name search $currentSearchData['name'] if needed
	 * 	For example : search with keyword "Tran Quoc Pagoda" will result in
	 * 		keyword = "Tran Quoc",
	 * 		category = "Pagoda" (e.g. 12 );
	 * 
	 * @TODO: Process city as well, for example "Tran Quoc Pagoda, Hanoi";
	 * @param $currentSearchData ....
	 * @return array with $currentSearchData['name'] present
	 * 
	 */
	public function filterKeyword($currentSearchData)
	{
		if(isset($currentSearchData['raw_name']))//&& isset($currentSearchData['reset']))
		{
			$userInput = $currentSearchData['raw_name'];
			//replace double white spaces with one white space character
			$str = preg_replace('/\s\s+/', ' ', $userInput );
			$strInput = strtolower(VN_unaccent(trim($str)));
			$filterKeywords = array('28' => 'khach san 1 sao',
									'29' => 'khach san 2 sao',
									'30' => 'khach san 3 sao',
									'31' => 'khach san 4 sao', 
									'32' => 'khach san 5 sao',
									'33' => 'nha nghi',
									'3' => 'khach san',
									'37' => 'chua',
									'2' => 'nha hang',
									'4' => 'bar',
									'4' => 'cafe',
									'8' => 'dai su quan',
									'12' => 'atm',
									'12' => 'ngan hang',
									);
			foreach($filterKeywords as $key => $val)
			{
				if(strncmp($strInput, $val, strlen($val)) == 0)
				{
					$currentSearchData['name'] = trim(str_replace($val, "",$strInput));
					$ret = $this->mCategory->getTree($key, 0, 1);
					foreach($ret as $k => $v)
					{
						$count = count(explode('_', $v['tree_path']));
						if($count == 4 && empty($currentSearchData['rtype']))
							$currentSearchData['rtype'] = $key;
						else if($count == 5 && empty($currentSearchData['type']))
						{
							$rtype = explode('_', $v['tree_path']);
							$currentSearchData['rtype'] = $rtype[3];
							if($rtype[3] != $key)
								$currentSearchData['type'] = $v['id'];
						}
						else if($count == 6)
						{
							$currentSearchData['rtype'] = $v['pid'];
							$currentSearchData['type'] = $v['id'];
						}
					}
					break;
				}
				if(empty($currentSearchData['rtype']))
					$currentSearchData['name'] = $currentSearchData['raw_name'];
			}
		}
		else
		{
			if(isset($currentSearchData['search_name']))
				$currentSearchData['name'] = $currentSearchData['search_name'];
		}
//		die_a($currentSearchData);
		return $currentSearchData;
	}
	
	public function unsetSearchValues($currentSearchData, $arrayKeys)
	{
		foreach($arrayKeys as $k)
			unset($currentSearchData[$k]);
	}
	
	public function mergeSearchValues($requestData, $currentSearchData, $arrayKeys, $unset)
	{
		foreach($arrayKeys as $k)
		{
			if (isset($requestData[$k]) && !empty($requestData[$k]))
				$currentSearchData[$k] = $requestData[$k];
			else if ($unset)	
				unset($currentSearchData[$k]);
			//else, keep the $currentSearchData[$k]
		}
		return $currentSearchData;
	}
	
	public function mergeHierarchySearchValues($requestData, $currentSearchData, $addressKeys, $indexToUnset)
	{					
		foreach ($addressKeys as $keyIndex => $key)
		{
			if (!isset($requestData[$key]))
				continue;
			//now isset($requestData[$key]) == true
			else
			{
				//echo "<h1> $keyIndex : $key </h1> current search data: $currentSearchData[$key] <br/> request data {$requestData[$key]} <hr/>";
				if (
						($keyIndex < $indexToUnset) // in range that will cause reset
						&& 
						(
							(isset($currentSearchData[$key]) && ($requestData[$key] != $currentSearchData[$key]))
								||
							(!isset($currentSearchData[$key]))
						)
					)
				{
					//change key value first
					$currentSearchData[$key] = $requestData[$key];
					$addressKeysToUnset = array();
					//$keyToUnset = $addressKeys' subarray from $keyIndex + 1 -> last
					for ($i = $keyIndex + 1; $i < count($addressKeys); $i++)
					{
							$addressKeysToUnset [] = $addressKeys[$i];
					}
					$currentSearchData = $this->mergeSearchValues($requestData, $currentSearchData, $addressKeysToUnset , true);
					//if value of $keyIndex is empty then unset value of $keyIndex+1
					if(empty($currentSearchData[$key]))
					{
						unset($currentSearchData[$key]);
						unset($currentSearchData[$addressKeys[$keyIndex+1]]);
					}
					break; //break after merge & unset the remaining values
				}
				else //only set 1 value
				{
					if ($requestData[$key] == '-1000')
					{
						unset($currentSearchData[$key]);
					}
					else
						$currentSearchData[$key] = $requestData[$key];
				}
			} 
		}
		return $currentSearchData;
	}
	
	public function addNewArticleAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$this->viewParams['place_id'] = $this->_request->getParam('place_id');
		$this->viewParams['other_article_id'] = $this->_request->getParam('other_article_id');
		$this->viewParams['edit'] = $this->_request->getParam('edit');
		$this->viewParams['remove'] = $this->_request->getParam('remove');
		$this->viewParams['form'] = new place_Form_Place();
		$actionUrl = $this->hvnUrl(array('module' => 'place', 'action'=>'add-new-article'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'add-article', 'action_url' => $actionUrl, 
							  'userPermissions' => $sess->userPermissions));
		
		// if remove == 1 then delete article_id in articles table && remove element in metadata of place
		if(isset($this->viewParams['remove']) && $this->viewParams['remove'] == 1)
		{
			$articleIds[] =  $this->viewParams['other_article_id'];
			$this->mArticle->deleteByPrimary($articleIds);
			try
		    {
		    	$data['id'] = $this->viewParams['place_id'];
		    	$data['remove'] = 1; 
		    	$data['other_article_id'] = $this->viewParams['other_article_id'];
		    	$p = $this->m->findByPrimary($data['id']);
		    	if (!($this->m->saveRaw($p, $data, $data['id'], false)))
	            {
	            	$this->viewParams['successMessage'] = t(731);
	            }
		    	
		    }
		    catch (Exception $e) 
            {
                $this->viewParams['errorMessage'] = t(727);
            }
		}
		
		if($this->_request->isGet() && $this->viewParams['edit'] == 1)
		{
			if(isset($this->viewParams['other_article_id']) && !isset($this->viewParams['remove']))
			{
				$dataDisplay = $this->m->getData($this->viewParams['place_id'], $options = null);
				$data = unserialize($dataDisplay['metadata']);
				$aData['article_body'] = $this->mArticle->getArticleData($this->viewParams['other_article_id'])->article_body;
				foreach($data['other_article'] as $o)
				{
					if($this->viewParams['other_article_id'] == $o['other_article_id'])
					{
						$aData['name'] = $o['article_title']['title'];
						$aData['language'] = $o['article_title']['language'];
						$aData['article_weight'] = $o['weight'];
					}
				}
				$this->viewParams['form']->populate($aData);
			}
		}
		
		$auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST))
        {	
        	$data = $this->_request->getParams();
        	// update article
        	$articleData['article_title'] = $data['name'];
        	$articleData['article_language'] = $data['article_language'];
        	$db = $this->db;
	        $db->beginTransaction();
	        if(empty($this->viewParams['other_article_id']))
	        {
	        	//$articleData['article_module'] = $data['article_module'];
	        	//$articleData['article_keywords'] = $data['article_keywords'];
	        	$articleData['article_body'] = $data['article_body'];
	        	
	            if (!($this->mArticle->insertRaw($articleData, false)))
	            {
	            	$this->viewParams['errorMessage'] = t(503);
	            }
	            $article_id = $db->lastInsertId();
	            $data['other_article_id'] = $article_id;
	        }
	        else
            {
            	if (!$a = $this->mArticle->findByPrimary($this->viewParams['other_article_id']))
				{
					$this->renderError(null,t(504));
					return;	                                                                                                                                                                   
		        }
           		$this->mArticle->saveRaw($a, $articleData, $this->viewParams['other_article_id'], false);
            }
	        
		    try
		    {
	            $data['poster_id'] = $uIdentity->id;
		    	$p = $this->m->findByPrimary($data['id']);
		    	if ($this->m->saveRaw($p, $data, $data['id'], false))
	            {
	            	$this->viewParams['successMessage'] = t(731);
	            }
		    	
		    }
		    catch (Exception $e) 
            {
                $this->viewParams['errorMessage'] = t(727);
            }
        }
	}
	
	public function viewArticleOfPlaceAction()
	{
		$this->viewParams['place_id'] = $this->_request->getParam('id');
		$this->viewParams['other_article_id'] = $this->_request->getParam('other_article_id');
		$sess = new Zend_Session_Namespace(CLU_NS);
		$dataDisplay = $this->m->getData($this->viewParams['place_id'], $options = null);
		$articleDataDisplay = $this->mArticle->getArticleData($this->viewParams['other_article_id']);
		$this->paramsForWidgets['place_id'] = $this->viewParams['place_id'];
		$data = unserialize($dataDisplay['metadata']);
		$this->paramsForWidgets['listArticle'] = $data['other_article'];
        
        if(!$articleDataDisplay)
        {
            $this->renderError(null,t(724));
            return;
        }
        if(!empty($articleDataDisplay))
        {
	        //get data for display
	        $this->viewParams['article_body'] = $articleDataDisplay->article_body;
	        $this->viewParams['article_title'] = $articleDataDisplay->article_title;
	        $this->viewParams['lang'] = $sess->viewLang;
	        $this->viewParams['oriLang'] = $articleDataDisplay->article_language;
        }
	}
	
	public function manageFeaturedPlaceAction()
	{
		$data = array('status' => 'featured');
		$results = $this->m->search($data);
		$this->viewParams['displayData'] = $this->db->fetchAll($results);
	}
}
?>
